package com.unlcn.ils.sales.backend.service;

import cn.huiyunche.commons.exception.BusinessException;
import cn.huiyunche.commons.utils.HttpRequestUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.unlcn.ils.sales.backend.bo.OrderAuditBO;
import com.unlcn.ils.sales.backend.bo.OrderToKyleBO;
import com.unlcn.ils.sales.backend.bo.PriceBO;
import com.unlcn.ils.sales.backend.constant.AutoConfConstant;
import com.unlcn.ils.sales.backend.enums.OrderAuditStatusEnum;
import com.unlcn.ils.sales.backend.util.DateUtils;
import com.unlcn.ils.sales.base.mapper.SaleOrderAuditMapper;
import com.unlcn.ils.sales.base.mapper.SaleOrderViewMapper;
import com.unlcn.ils.sales.base.model.OrderViewDAO;
import com.unlcn.ils.sales.base.model.SaleOrderAudit;
import com.unlcn.ils.sales.base.model.SaleOrderAuditExample;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * Created by houjianhui on 2017/6/12.
 */
@Service
public class OrderAuditServiceImpl implements OrderAuditService {

    private static final Logger LOGGER = LoggerFactory.getLogger(OrderAuditServiceImpl.class);

    @Autowired
    private SaleOrderAuditMapper orderAuditMapper;

    @Autowired
    private AutoConfConstant autoConfConstant;

    @Autowired
    private SaleOrderViewMapper orderViewMapper;

    @Override
    public Integer save(Integer saleOrderId, String saleOrderCode) throws Exception {
        LOGGER.info("OrderAuditServiceImpl.save params saleOrderId: {}, saleOrderCode: {}", saleOrderId, saleOrderCode);
        if (Objects.equals(saleOrderId, null) || Objects.equals(saleOrderId, "") || Objects.equals(saleOrderId, 0)) {
            LOGGER.info("OrderAuditServiceImpl.save param saleOrderId must not be null");
            throw new IllegalArgumentException("销售订单ID不能为空");
        } else if (StringUtils.isBlank(saleOrderCode)) {
            LOGGER.info("OrderAuditServiceImpl.save param saleOrderCode must not be null");
            throw new IllegalArgumentException("销售订单编号不能为空");
        }
        SaleOrderAudit audit = new SaleOrderAudit();
        audit.setSaleOrderId(saleOrderId);
        audit.setSaleOrderCode(saleOrderCode);
        audit.setAuditStatus(OrderAuditStatusEnum.ORDER_INIT.getValue());

        try {
            return orderAuditMapper.insertSelective(audit);
        } catch (Exception e) {
            LOGGER.error("OrderAuditServiceImpl.save error: {}", e);
            throw new BusinessException("保存销售订单审核信息异常");
        }
    }

    @Override
    public Integer update(OrderAuditBO bo) throws Exception {
        LOGGER.info("OrderAuditServiceImpl.update param OrderAudit: {}", bo);
        if (Objects.equals(bo, null) || Objects.equals(bo, "")) {
            LOGGER.info("OrderAuditServiceImpl.update param OrderAudit must not be null");
            throw new IllegalArgumentException("销售订单审核信息不能为空");
        }
        SaleOrderAudit audit = null;
        try {
            SaleOrderAuditExample example = new SaleOrderAuditExample();
            example.createCriteria().andSaleOrderIdEqualTo(bo.getId());
            List<SaleOrderAudit> audits = orderAuditMapper.selectByExample(example);
            if (CollectionUtils.isNotEmpty(audits)) {
                audit = audits.get(0);
            }
        } catch (Exception e) {
            LOGGER.error("OrderAuditServiceImpl.update select OrderAudit error: {}", e);
            throw new BusinessException("查询销售订单审核信息异常");
        }
        if (Objects.equals(audit, null)) {
            LOGGER.info("OrderAuditServiceImpl.update Current orderAudit doesn't exist");
            throw new BusinessException("销售订单审核信息不存在");
        }
        audit.setAuditUser(bo.getAuditUser());
        audit.setAuditStatus(bo.getAuditStatus());
        audit.setComment(bo.getComment());
        try {
            return orderAuditMapper.updateByPrimaryKeySelective(audit);
        } catch (Exception e) {
            LOGGER.error("OrderAuditServiceImpl.update error: {}", e);
            throw new BusinessException("更新销售订单审核信息异常");
        }
    }

    @Override
    public Integer updateAuditStatus(String ids) throws Exception {
        LOGGER.info("OrderAuditServiceImpl.updateAuditStatus param ids: {}", ids);
        if (Objects.equals(ids, null) || Objects.equals(ids, "")) {
            LOGGER.info("OrderAuditServiceImpl.updateAuditStatus ids must not be null");
            throw new IllegalArgumentException("销售订单审核ID不能为空");
        }
        String[] idStr = ids.split(",");
        if (!Objects.equals(idStr, null)) {
            Map<String, Object> queryMap = new HashMap<>();
            queryMap.put("ids", idStr);
            Map<String, Object> saleOrderMap = new HashMap<>();

            try {
                orderViewMapper.updateAuditStatus(queryMap);
            } catch (Exception e) {
                LOGGER.error("OrderAuditServiceImpl.updateAuditStatus error: {}", e);
                throw new BusinessException("更新销售订单审核状态异常");
            }

            try {
                orderViewMapper.updateOrderStatus(queryMap);
            } catch (Exception e) {
                LOGGER.error("OrderAuditServiceImpl.updateAuditStatus error: {}", e);
                throw new BusinessException("更新销售订单状态异常");
            }
            List<OrderToKyleBO> bos = buildOrderToKyleBO(orderViewMapper.listSaleOrder(queryMap));
            String jsonArray = JSONArray.toJSONString(bos);
            if (CollectionUtils.isNotEmpty(bos)) {
                saleOrderMap.put("saleOrder", jsonArray);
                pushSaleOrderToKyle(saleOrderMap);
            }
        }
        return null;
    }

    @Override
    public void updateAuditStatusByOrderId(Integer saleOrderId, Integer auditStatus) {
        if (Objects.equals(saleOrderId, null) || Objects.equals(saleOrderId, "") || Objects.equals(saleOrderId, 0)) {
            LOGGER.info("OrderAuditServiceImpl.updateAuditStatusByOrderId param saleOrderId must not be null");
            throw new IllegalArgumentException("销售订单ID不能为空");
        } else if (Objects.equals(auditStatus, null) || Objects.equals(auditStatus, "") || Objects.equals(auditStatus, 0)) {
            LOGGER.info("OrderAuditServiceImpl.updateAuditStatusByOrderId param auditStatus must not be null");
            throw new IllegalArgumentException("销售订单审核状态不能为空");
        }
        SaleOrderAuditExample example = new SaleOrderAuditExample();
        example.createCriteria().andSaleOrderIdEqualTo(saleOrderId);
        List<SaleOrderAudit> audits = orderAuditMapper.selectByExample(example);
        if (CollectionUtils.isNotEmpty(audits)) {
            audits.stream().forEach(item -> {
                item.setAuditStatus(auditStatus);
                orderAuditMapper.updateByPrimaryKeySelective(item);
            });
        }

    }

    /**
     * 构建推送销售订单对象
     *
     * @param daos
     * @return
     */
    private List<OrderToKyleBO> buildOrderToKyleBO (List<OrderViewDAO> daos) {
        if (CollectionUtils.isNotEmpty(daos)) {
           List<OrderToKyleBO> bos = new ArrayList<>();
           daos.stream().forEach(val -> {
               OrderToKyleBO bo = new OrderToKyleBO();
               bo.setUserId(val.getUserId());
               bo.setOrderCode(val.getCode());
               bo.setDepartRegionCode(val.getDepartRegionCode());
               bo.setDepartRegionName(val.getDepartRegionName());
               bo.setDepartContact(val.getDepartContact());
               bo.setDepartPhone(val.getDepartPhone());
               bo.setDestRegionCode(val.getDestRegionCode());
               bo.setDestRegionName(val.getDestRegionName());
               bo.setDestContact(val.getDestContact());
               bo.setDestPhone(val.getDestPhone());
               String pickDate = DateUtils.getStringFromDate(val.getPickDate(), "yyyy-MM-dd");
               bo.setPickDate(pickDate);
               bo.setBrands(val.getBrands());
               bo.setSeriesAmt(val.getSeriesAmt());
               bo.setDistance(val.getDistance().toString());
               bo.setOrderCost(val.getSuggestSalePrice().toString());
               bo.setBxCost(val.getInsuranceSalePrice().toString());
               bo.setOrderSku(JSONArray.toJSONString(val.getOrderSkus()));
               bo.setComment(val.getComment());
               bo.setIsPick(val.getIsPick());
               bo.setIsDeliv(val.getIsDeliv());
               bo.setIsTicket(val.getIsTicket());
               bo.setTransportType(val.getTransportType());
               bo.setDepartAddr(val.getDepartAddr());
               bo.setDestAddr(val.getDestAddr());
               bo.setPickTime(val.getPickTime());
               bos.add(bo);
           });
           return bos;
        }
        return null;
    }

    /**
     * 推送销售订单到商户端
     *
     * @param map 推送数据
     * @throws Exception
     */
    private void pushSaleOrderToKyle(Map<String, Object> map) throws Exception {
        String url = autoConfConstant.getKyle() + "/saleOrder/syncSaleOrder";
        Integer time = autoConfConstant.getKyleTime();
        String result = HttpRequestUtil.sendHttpPost(url, map, time);
        if (!Objects.equals(result, null)) {
            JSONObject jsonObject = JSONObject.parseObject(result);
            String msgCode = jsonObject.getString("messageCode");
            String msg = jsonObject.getString("message");
            String data = jsonObject.getString("data");
            Boolean success = jsonObject.getBoolean("success");
            List<PriceBO> bos = JSONArray.parseArray(data, PriceBO.class);
            if (!success) {
                LOGGER.info("OrderServiceImpl pushSaleOrderToKyle result error");
                throw new BusinessException(msgCode, msg);
            }
        }
    }

}
